﻿Chenxin.UI.BusinessApplyMain = Chenxin.extend(Chenxin.UI.FormCommon, {
    actionUrl: "/service/ContractApply/ContractApply.ashx",
    //actionUrl1: "/service/ContractApply/ContractHandler.ashx",
    id: "divMainBusiness",
    type: 'numal',
    initEvent: function() {
        var _this = this;
        $('.x_colexp').collapse({
            getDom: function() {
                return $('#' + this.id.replace('x_btn_col_', 'div_form_'));
            }
        });

        $('#aSubmit').bind('click', { scope: this }, function(e) {
            e.data.scope.save();
        });

        this.findByName('BusinessType').click(function() {
            _this.getStandardCommission();
        });

        this.findByName('BargainPrice').change(function() {
            _this.getStandardCommission();
        });

        $('#x_view_marked').live('click', function() {
            _this.viewMarked();
        });

        $('#x_view_key').live('click', function() {
            _this.viewKey();
        });

        $('#x_btn_redirect').click(function() {
            if (confirm('确定' + $(this).find('span').html() + '吗？')) {
                switch (_this.op) {
                    case 'confirmview':
                    case 'confirmedit': //确认编辑
                        window.location.href = '/page/Contract_ApplyInfo/ShowListBargain.aspx';
                        break;
                    case 'add': //添加
                        history.go(-1);
                        break;
                    default: //默认
                        window.location.href = '/page/Contract_ApplyInfo/ShowListContractApply.aspx';
                        break;
                }
            }
            return false;
        });

    },
    viewMarked: function() {
        if (!this.markedWin) {
            this.markedWin = new Chenxin.UI.MarkedWin({
                scope: this
            });
        }

        this.markedWin.grid.param.houseid = Chenxin.Fn.getQueryString('HouseId') || this.currentInfo.HouseId;
        this.markedWin.grid.reload();
        this.markedWin.show();

    },
    viewKey: function() {
        if (!this.keyWin) {
            this.keyWin = new Chenxin.UI.KeyWin({
                scope: this
            });
        }

        this.keyWin.grid.param.houseid = Chenxin.Fn.getQueryString('HouseId') || this.currentInfo.HouseId;
        this.keyWin.grid.reload();
        this.keyWin.show();
    },
    save: function() {
        var msg = '';
        if (this.op == 'edit' || this.op == 'confirmedit') {
            msg = '是否提交修改？';
        }
        else if (this.op == 'confirme') {
            msg = '是否确认所属公司为：“' + this.findByName('BargainCompanyId').getText() + '”的“';
            this.findByName('BusinessType').each(function() {
                if (this.checked) {
                    msg += this.value == '10' ? '买卖' : '租赁';
                    return false;
                }
            });
            msg += '”成交申请？';
        }
        else {
            msg = '确定提交所属公司为：“' + this.findByName('BargainCompanyId').getText() + '”的“';
            this.findByName('BusinessType').each(function() {
                if (this.checked) {
                    msg += this.value == '10' ? '买卖' : '租赁';
                    return false;
                }
            });
            msg += '”成交编号申请确认？';
        }
        if (confirm(msg)) {
            Chenxin.UI.BusinessApplyMain.superclass.save.call(this);
        }
    },
    getStandardCommission: function() {

        var type;
        this.findByName('BusinessType').each(function() {
            if (this.checked) {
                type = this.value;
                return false;
            }
        });
        var bPrice = this.findByName('BargainPrice').val();
        var property = this.findByName('HouseProperty');


        if (type != '' && bPrice != '' && property && property.getValue() != property.defVal) {
            Chenxin.ajax({
                type: "post",
                dataType: "json",
                url: this.actionUrl,
                data: { op: 'getstandcomm', BusinessType: type, HouseProperty: property.getValue(), BargainPrice: bPrice },
                onSuccess: function(data) {
                    $("#txtVStandardCommision").val(data.VCommission);
                    $("#txtBStandardCommision").val(data.BCommission);
                }
            });
        } else {
            $("#txtVStandardCommision").val("");
            $("#txtBStandardCommision").val("");
        }
        if (type == '10') {
            $('#FixDiscount_tr').show();
            $("#txtFixDiscount").unFormValidator(false);
        }
        else {
            $('#FixDiscount_tr').hide();
            $("#txtFixDiscount").unFormValidator(true);
        }
    },
    saveSucc: function() {
        //提交成功后转到查询页面
        var url = '';
        this.op = Chenxin.Fn.getQueryString('op') || 'add';
        if (this.op != 'confirmedit')
            url = 'ShowListContractApply.aspx';
        else
            url = 'ShowListBargain.aspx';
        window.location.href = "/page/Contract_ApplyInfo/" + url;
        //window.location.href = "/page/Contract_ApplyInfo/ShowListContractApply.aspx";
    },
    formPartId: {
        fp_0: '',
        fp_10: 'div_form_1,div_form_2,div_form_5',
        fp_20: 'div_form_4,grid',
        fp_30: 'div_form_3',
        fp_40: '',
        fp_50: 'all'
    },
    setPartDisable: function() {//封帐状态：0=未封；10=解封资料;20=解封业绩分配;30=佣收情况；40=成交瑕疵；50=全封
        if (this.op != 'confirmedit') {
            return;
        }

        var lockStatus = this.currentInfo.LockStatus;
        var archFlg = this.currentInfo.bArchivement;
        //判断最基本资料是否封盘0001(1);
        if ((lockStatus & 1) && archFlg) {
            Chenxin.Fn.setFormDisable('div_form_1', this.comboList);
            Chenxin.Fn.setFormDisable('div_form_2', []);
            Chenxin.Fn.setFormDisable('div_form_5', []);
        }
        //判断佣金资料是否封盘0010(2);
        if ((lockStatus & 2) && archFlg) Chenxin.Fn.setFormDisable('div_form_3', []);

        //判断点数资料是否封盘0100(4);
        if ((lockStatus & 4) && archFlg) {
            Chenxin.Fn.setFormDisable('div_form_4', []);
            this.grid.opstatus = false;
        }

        //买卖类型及合同所属公司不允许修改
        this.findByName('BusinessType').disable();
        this.findByName('BargainCityId').setDisable();
        this.findByName('BargainCompanyId').setDisable();
    },
    createComboList: function() {
        //获取初始Combo的值
        var _this = this;
        var op = Chenxin.Fn.getQueryString('op');


        //区域
        var comboRegion = new Chenxin.UI.ParameterCombo({
            name: 'Region',
            containerId: '#Region',
            key: 'System.Region',
            tbxWidth: 120,
            inModelType: 'txt',
            required: true,
            param: { filter: 'bycity' },
            onSelected: function() {
                if (this.getValue() == this.defVal) {
                    comboBlock.clearItems();
                } else {
                    comboBlock.param.subkey = this.getValue();
                    comboBlock.param.recordid = this.getValueRecord()['id'];
                    comboBlock.reload();
                }
            },
            afterSetValue: function(newVal, oldVal) {
                if (newVal != this.defVal) {
                    comboBlock.param.subkey = this.getValue();
                    comboBlock.param.recordid = this.getValueRecord()['id'];
                    comboBlock.reload(_this.currentInfo.Block);
                } else {
                    comboBlock.reset();
                }
            }
        });
        //板块
        var comboBlock = new Chenxin.UI.ParameterCombo({
            containerId: '#Block',
            key: 'System.Block',
            tbxWidth: 120,
            colWidth: 90,
            inModelType: 'txt',
            autoLoad: false,
            required: false
        });
        //合同归属（城市）
        var comboBargainCityId = new Chenxin.UI.StructCombo({
            param: { op: 'getcity' },
            containerId: '#BargainCityId',
            name: 'BargainCityId',
            tbxWidth: 120,
            inModelType: 'all',
            txtModelName: 'BargainCityName',
            onSelected: function() {
                if (this.getValue() == this.defVal) {
                    comboBargainCompanyId.clearItems();
                } else {
                    comboBargainCompanyId.param.fatherid = this.getValue();
                    comboBargainCompanyId.reload();
                }
            },
            afterSetValue: function(newVal, oldVal) {
                if (newVal != this.defVal) {
                    comboBargainCompanyId.param.fatherid = newVal;
                    comboBargainCompanyId.reload(_this.currentInfo.BargainCompanyId);
                } else {
                    comboBargainCompanyId.reset();
                }
            }
        });
        //合同归属（公司）
        var comboBargainCompanyId = new Chenxin.UI.StructCombo({
            param: { op: 'getcompany' },
            containerId: '#BargainCompanyId',
            name: 'BargainCompanyId',
            inModelType: 'all',
            txtModelName: 'BargainCompanyName',
            tbxWidth: 120,
            autoLoad: false,
            required: true,
            onSelected: function() {
                if (this.getValue() != this.defVal) {
                    Chenxin.ajax({
                        type: "get",
                        dataType: "json",
                        url: '/service/ContractApply/ContractApply.ashx',
                        data: { op: 'getfixdiscount', CompanyId: this.getValue(), type: 10 },
                        onSuccess: function(data) {
                            $('#txtFixDiscount').val(data);
                        }
                    });
                }
            },
            afterSetValue: function(newVal, oldVal) {
                if (newVal != this.defVal && op == null) {
                    Chenxin.ajax({
                        type: "get",
                        dataType: "json",
                        url: '/service/ContractApply/ContractApply.ashx',
                        data: { op: 'getfixdiscount', CompanyId: newVal, type: 10 },
                        onSuccess: function(data) {
                            $('#txtFixDiscount').val(data);
                        }
                    });
                }
            }
        });

        //下家门店
        var comboBuyerDepartId = new Chenxin.UI.DepartTreeCombo({
            containerId: '#txtBuyerDepartId',
            textBoxId: 'txtBuyerDepartId',
            name: 'BuyerDepartId',
            inModelType: 'all',
            txtModelName: 'BuyerDepartName',
            required: true,
            afterSetValue: function(val, txt) {
                if (val != this.defVal) {
                    comboBuyerUserId.loadUser(val)
                }
            },
            onSelected: function() {
                if (this.getValue() != this.defVal) {
                    comboBuyerUserId.loadUser(this.getValue());
                }
            }
        });
        //下家业务员
        var comboBuyerUserId = new Chenxin.UI.RichModelTreeCombo({
            containerId: '#txtBuyerUserId',
            textBoxId: 'txtBuyerUserId',
            inModelType: 'all',
            txtModelName: 'BuyerUserName',
            required: true,
            singleSelect: true,
            name: 'BuyerUserId'
        });
        //房屋用途
        var comboHouseUse = new Chenxin.UI.ParameterCombo({
            containerId: '#HouseUse',
            name: 'HouseUse',
            key: 'House.Use',
            inModelType: 'txt',
            tbxWidth: 120,
            required: true
        });
        //建筑类型
        var comboBuildingType = new Chenxin.UI.ParameterCombo({
            containerId: '#BuildingType',
            name: 'BuildingType',
            key: 'Building.Type',
            inModelType: 'txt',
            autoLoad: true,
            tbxWidth: 120,
            required: true
        });
        //客户来源
        var comboCustomerSource = new Chenxin.UI.Combo({
            containerId: '#CustomerSource',
            tbxWidth: 120,
            required: true,
            items: comboCommon.CustomerSource
        });
        //房屋性质
        var comboHouseProperty = new Chenxin.UI.Combo({
            containerId: '#HouseProperty',
            name: 'HouseProperty',
            tbxWidth: 120,
            colWidth: 80,
            required: true,
            items: comboCommon.HouseProperty,
            onSelected: function() {
                if (this.getValue() != this.defVal) {
                    _this.getStandardCommission();
                }
            }
        });
        var comboList = [comboRegion, comboBlock, comboBargainCityId,
				comboBargainCompanyId, comboBuyerDepartId, comboBuyerUserId, comboHouseUse,
				comboBuildingType, comboHouseProperty, comboCustomerSource];

        if (op == 'confirm' || op == 'confirmedit' || op == 'confirmview') {//确认业绩申请
            //签约人
            /*
            var comboWorkPersonId = new Chenxin.UI.StructCombo({
            param: { op: 'getemployee' },
            containerId: '#ContractUserId',
            inModelType: 'all',
            txtModelName: 'ContractUserName',
            //   autoLoad: false,
            required: true
            });*/
            //签约人
            var comboWorkPersonId = new Chenxin.UI.RichModelTreeCombo({
                containerId: '#ContractUserId',
                textBoxId: 'txtContractUserId',
                inModelType: 'all',
                txtModelName: 'ContractUserName',
                required: true,
                singleSelect: true,
                name: 'ContractUserId'
            });
            //签约地点（部门）
            var comboWorkDepartId = new Chenxin.UI.StructCombo({
                param: { op: 'getsigndeparts' },
                containerId: '#ContractDepartmentId',
                name: 'ContractDepartmentId',
                inModelType: 'all',
                tbxWidth: 120,
                txtModelName: 'ContractDepartmentName',
                required: true,
                afterSetValue: function(val, txt) {
                    if (val != this.defVal) {
                        comboWorkPersonId.loadUser(val)
                    }
                },
                onSelected: function() {
                    if (this.getValue() != this.defVal) {
                        comboWorkPersonId.loadUser(this.getValue());
                    }
                }
                /*
                onSelected: function() {
                if (this.getValue() == this.defVal) {
                comboWorkPersonId.clearItems();
                } else {
                comboWorkPersonId.param.fatherid = this.getValue();
                comboWorkPersonId.reload();
                }
                },
                afterSetValue: function(newVal, oldVal) {
                if (newVal != this.defVal) {
                comboWorkPersonId.param.fatherid = newVal;
                comboWorkPersonId.reload(_this.currentInfo.ContractUserId);
                }
                }*/
            });

            comboList.push(comboWorkPersonId, comboWorkDepartId);
        }
        return comboList;
    },
    initFormValidator: function() {
        //房源地址
        $("#txtNewHouseAddress").formValidator({
            validatorgroup: this.id,
            onshow: "请输入房源地址！",
            onfocus: "房源地址为必输项",
            oncorrect: " "
        }).inputValidator({
            min: 1,
            empty: {
                leftempty: false,
                rightempty: false,
                emptyerror: "房源地址不能为空！"
            },
            onerror: "房源地址不能为空！"
        });
        //面积
        $("#txtArea").formValidator({
            validatorgroup: this.id,
            onshow: "请输入面积！",
            onfocus: "面积为必输项",
            oncorrect: " "
        }).inputValidator({
            min: 1,
            empty: {
                leftempty: false,
                rightempty: false,
                emptyerror: "面积不能为空！"
            },
            onerror: "面积不能为空！"
        }).functionValidator({
            fun: function(val, elem) {
                return val.isNum();
            },
            onerror: "面积不能为非数值类型！"
        });
        //合同标的
        $("#txtBargainPrice").formValidator({
            validatorgroup: this.id,
            onshow: "请输入合同标的！",
            onfocus: "合同标的为必输项",
            oncorrect: " "
        }).inputValidator({
            min: 1,
            empty: {
                leftempty: false,
                rightempty: false,
                emptyerror: "合同标的不能为空！"
            },
            onerror: "合同标的不能为空！"
        }).functionValidator({
            fun: function(val, elem) {
                return val.isNum();
            },
            onerror: "非数值格式！"
        });
        //产权证号
        $("#txtPropertyCode").formValidator({
            validatorgroup: this.id,
            onshow: "请输入产权证号！",
            onfocus: "产权证号为必输项",
            oncorrect: " "
        }).inputValidator({
            min: 1,
            empty: {
                leftempty: false,
                rightempty: false,
                emptyerror: "产权证号不能为空！"
            },
            onerror: "产权证号不能为空！"
        });
        //上家姓名
        $("#txtVenderName").formValidator({
            validatorgroup: this.id,
            onshow: "请输入上家姓名！",
            onfocus: "上家姓名为必输项",
            oncorrect: " "
        }).inputValidator({
            min: 1,
            empty: {
                leftempty: false,
                rightempty: false,
                emptyerror: "上家姓名不能为空！"
            },
            onerror: "上家姓名不能为空！"
        });
        //上家身份证
        /* $("#txtVenderNo").formValidator({
        validatorgroup: this.id,
        onshow: "请输入上家身份证号！",
        onfocus: "上家身份证号为必输项",
        oncorrect: " "
        }).inputValidator({
        min: 1,
        empty: {
        leftempty: false,
        rightempty: false,
        emptyerror: "上家身份证号不能为空！"
        },
        onerror: "上家身份证号不能为空！"
        }).functionValidator({
        fun: function(val, elem) {
        return val.isIdCardNo();
        },
        onerror: "身份证格式不正确！"
        }); */
        //上家手机
        $("#txtVenderMobile").formValidator({
            validatorgroup: this.id,
            onshow: "请输入上家手机！",
            onfocus: "上家手机为必输项",
            oncorrect: " "
        }).inputValidator({
            min: 1,
            empty: {
                leftempty: false,
                rightempty: false,
                emptyerror: "上家手机不能为空！"
            },
            onerror: "上家手机不能为空！"
        }).functionValidator({
            fun: function(val, elem) {
                return val.isMobile();
            },
            onerror: "手机格式不正确！"
        });
        //下家姓名
        $("#txtBuyerName").formValidator({
            validatorgroup: this.id,
            onshow: "请输入下家姓名！",
            onfocus: "下家姓名为必输项",
            oncorrect: " "
        }).inputValidator({
            min: 1,
            empty: {
                leftempty: false,
                rightempty: false,
                emptyerror: "下家姓名不能为空！"
            },
            onerror: "下家姓名不能为空！"
        });
        //上家标准佣收
        $("#txtVStandardCommision").formValidator({
            validatorgroup: this.id,
            onshow: "请输入上家标准佣收！",
            onfocus: "上家标准佣收为金额格式",
            oncorrect: " "
        }).functionValidator({
            fun: function(val, elem) {
                return val.isNum();
            },
            onerror: "非金额格式！"
        }).inputValidator({
            min: 1,
            empty: {
                leftempty: false,
                rightempty: false,
                emptyerror: "上家标准佣收不能为空！"
            },
            onerror: "上家标准佣收不能为空！"
        });
        //下家标准佣收
        $("#txtBStandardCommision").formValidator({
            validatorgroup: this.id,
            onshow: "请输入下家标准佣收！",
            onfocus: "下家标准佣收为金额格式",
            oncorrect: " "
        }).functionValidator({
            fun: function(val, elem) {
                return val.isNum();
            },
            onerror: "非金额格式！"
        }).inputValidator({
            min: 1,
            empty: {
                leftempty: false,
                rightempty: false,
                emptyerror: "下家标准佣收不能为空！"
            },
            onerror: "下家标准佣收不能为空！"
        });
        //下家手机
        $("#txtBuyerMobile").formValidator({
            validatorgroup: this.id,
            onshow: "请输入下家手机！",
            onfocus: "下家手机为必输项",
            oncorrect: " "
        }).inputValidator({
            min: 1,
            empty: {
                leftempty: false,
                rightempty: false,
                emptyerror: "下家手机不能为空！"
            },
            onerror: "下家手机不能为空！"
        }).functionValidator({
            fun: function(val, elem) {
                return val.isMobile();
            },
            onerror: "手机格式不正确！"
        });
        //上家确认佣收
        $("#txtVRealCommision").formValidator({
            validatorgroup: this.id,
            onshow: "请输入上家确认佣收！",
            onfocus: "上家确认佣收为金额格式",
            oncorrect: " "
        }).functionValidator({
            fun: function(val, elem) {
                return val.isNum();
            },
            onerror: "非金额格式！"
        });
        //上家事前折佣
        $("#txtVCommision").formValidator({
            validatorgroup: this.id,
            onshow: "请输入上家事前折佣！",
            onfocus: "上家事前折佣为金额格式",
            oncorrect: " "
        }).functionValidator({
            fun: function(val, elem) {
                return val.isNum();
            },
            onerror: "非金额格式！"
        });
        //上家咨询费
        $("#txtVConsulting").formValidator({
            validatorgroup: this.id,
            onshow: "请输入上家咨询费！",
            onfocus: "上家咨询费为金额格式",
            oncorrect: " "
        }).functionValidator({
            fun: function(val, elem) {
                return val.isNum();
            },
            onerror: "非金额格式！"
        });
        //下家确认佣收
        $("#txtBRealCommision").formValidator({
            validatorgroup: this.id,
            onshow: "请输入下家确认佣收！",
            onfocus: "下家确认佣收为金额格式",
            oncorrect: " "
        }).functionValidator({
            fun: function(val, elem) {
                return val.isNum();
            },
            onerror: "非金额格式！"
        });
        //下家事前折佣
        $("#txtBCommision").formValidator({
            validatorgroup: this.id,
            onshow: "请输入下家事前折佣！",
            onfocus: "下家事前折佣为金额格式",
            oncorrect: " "
        }).functionValidator({
            fun: function(val, elem) {
                return val.isNum();
            },
            onerror: "非金额格式！"
        });
        //下家咨询费
        $("#txtBConsulting").formValidator({
            validatorgroup: this.id,
            onshow: "请输入下家咨询费！",
            onfocus: "下家咨询费为金额格式",
            oncorrect: " "
        }).functionValidator({
            fun: function(val, elem) {
                return val.isNum();
            },
            onerror: "非金额格式！"
        });
        //上家标准佣收
        $("#txtFixDiscount").formValidator({
            validatorgroup: this.id,
            onshow: "请输入固定折让！",
            onfocus: "固定折让为金额格式",
            oncorrect: " "
        }).functionValidator({
            fun: function(val, elem) {
                return val.isNum();
            },
            onerror: "非金额格式！"
        }).inputValidator({
            min: 1,
            empty: {
                leftempty: false,
                rightempty: false,
                emptyerror: "固定折让不能为空！"
            },
            onerror: "固定折让不能为空！"
        });
    },
    initPageInfo: function() {

        var opbtn = $('#x_btn_redirect');
        var title = '';
        var isConfirm = false;
        var redirect = '';

        switch (this.op) {
            case 'confirm':
                title = '主营业务成交编号申请确认';
                isConfirm = true;
                redirect = '返回成交记录管理';
                break;
            case 'confirmedit':
                title = '主营业务成交记录修改';
                isConfirm = true;
                redirect = '返回成交记录管理';
                //this.actionUrl = this.actionUrl1;
                break;
            case 'edit':
                title = '主营业务成交编号申请修改';
                isConfirm = false;
                redirect = '返回业绩申请管理';
                break;
            case 'view':
                title = '主营业务成交编号申请查看';
                isConfirm = false;
                redirect = '返回业绩申请管理';
                $('#aSubmit').remove();
                this.grid.opstatus = false;
                this.setDisable();
                break;
            case 'confirmview':
                title = '主营业务成交记录查看';
                isConfirm = true;
                redirect = '返回成交记录管理';
                //this.actionUrl = this.actionUrl1;
                $('#aSubmit').remove();
                this.grid.opstatus = false;
                this.setDisable();
                break;
            case 'add':
                title = '主营业务成交编号申请';
                isConfirm = false;
                redirect = '返回房源列表';
                break;
        }

        $('#div_form_confirm')[isConfirm ? 'show' : 'remove']();
        //$('#x_not_confirminfo')[isConfirm ? 'remove' : 'show']();
        $('#x_span_title').html(title);
        opbtn.find('span').html(redirect);
        document.title = title;
    },
    initData: function() {
        var recordId = Chenxin.Fn.getQueryString('RecordId');
        var houseId = Chenxin.Fn.getQueryString('HouseId');
        var modelId = recordId || houseId;


        this.op = Chenxin.Fn.getQueryString('op') || 'add';

        this.initPageInfo();

        if (modelId) {
            Chenxin.Fn.getModel(modelId, this.actionUrl, function(data) {
                var model = {};
                if (this.op == 'add') {//添加主营业务	
                    this.houseInfo = data.houseInfo;
                    this.userInfo = data.userInfo;
                    Chenxin.apply(model, this.houseInfo);
                    model.HouseAddress = this.houseInfo.DetailAddress;
                    model.Area = this.houseInfo.BuildingArea;
                    model.CurrentFloor = this.houseInfo.Cur_Floor;
                    model.TotalFloor = this.houseInfo.Total_Floor;

                    //上家门店
                    model.VenderDepartName = this.houseInfo.OprDepart;
                    model.VenderDepartId = this.houseInfo.OprDepartId;
                    //上家业务员
                    model.VenderUserName = this.houseInfo.OprPerson;
                    model.VenderUserId = this.houseInfo.OprPersonId;

                    //下家门店
                    model.BuyerDepartId = this.userInfo.DepartId;
                    model.BuyerDepartName = this.userInfo.DepartName;

                    //下家业务员
                    //model.BuyerUserId = this.userInfo.UserId;
                    //model.BuyerUserName = this.userInfo.UserName;

                    //合同所属城市、合同所属公司
                    model.BargainCityId = this.houseInfo.CityId;
                    model.BargainCompanyId = this.userInfo.CompanyId;

                    //固定折让为0
                    //model.FixDiscount = 0;

                    this.initGridData();
                } else {//编辑、确认主营业务
                    this.applyInfo = data.applyInfo;
                    if (this.applyInfo.FixDiscount == undefined) {
                        this.applyInfo.FixDiscount = '0';
                    }
                    Chenxin.apply(model, this.applyInfo);

                    if (this.op == 'confirmedit' || this.op == 'confirmview') {

                        model.VStandardCommision = model.VStanCommision;
                        model.BStandardCommision = model.BStanCommision;
                        $('#DoneDay').val(model.ContractDate.substr(0, 10));
                    }

                    this.initGridData(data.pointList);
                }
                this.currentInfo = model;
                this.fitData(model);

                if (data.hasKey) {//有钥匙
                    $('#showdiv').after('<div style="float:right;"><a title="查看钥匙" id="x_view_key" class="red20" style="margin-right:10px;cursor:pointer;">查看钥匙</a></div>');
                }
                if (data.hasMarked) {//有有备案
                    $('#showdiv').after('<div style="float:right;"><a title="查看备案" id="x_view_marked" class="red20" style="margin-right:10px;cursor:pointer;">查看备案</a></div>');
                }
                this.setPartDisable();

                if (model.BusinessType != 10) {
                    $('#FixDiscount_tr').hide();
                    $("#txtFixDiscount").unFormValidator(true);
                }
                if (this.op == 'add') {
                    $('#FixDiscount_tr').show();
                    $("#txtFixDiscount").unFormValidator(false);
                }

            }, this, (this.op == 'confirmedit' || this.op == 'confirmview') ? 'getconfirminitdata' : 'getinitdata', { type: (recordId ? 'edit' : 'add') });
        }
    },

    initGridData: function(store) {
        if (!store) {
            Chenxin.Fn.getModel(this.houseInfo.OprDepartId, this.actionUrl, function(data) {
                var record = 'abc_' + Math.random() * 10000000000;
                record = record.replace('.', '');
                var row = {
                    Point: 2,
                    RecordId: record,
                    BuyerOrVenderInfo: '10',
                    EmployeeId: this.houseInfo.OprPersonId,
                    Employee: this.houseInfo.OprPerson,
                    DepartId: this.houseInfo.OprDepartId,
                    Depart: this.houseInfo.OprDepart
                };
                Chenxin.apply(row, data);
                this.grid.render({
                    rows: [row],
                    count: 1
                });
            }, this, 'getparents');
        } else {
            this.grid.render(store);
        }
    },
    createGrid: function() {
        if (!this.grid) {
            var _this = this;
            this.grid = new Chenxin.UI.PointGrid({
                actionUrl: this.actionUrl,
                getFormInitData: function(data) {

                    var _user = this.findByName('BuyerUserId');
                    var _depart = this.findByName('BuyerDepartId');

                    if (_depart.getValue() != this.defVal) {
                        data.DepartId = _depart.getValue();
                        data.Depart = _depart.getText();
                    } else {
                        data.DepartId = '';
                        data.Depart = '';
                    }
                    if (_user.getValue() != this.defVal) {
                        data.EmployeeId = _user.getValue();
                        data.Employee = _user.getText();
                    } else {
                        data.EmployeeId = '';
                        data.Employee = '';
                    }

                    /* if(this.userInfo){
                    Chenxin.apply(data,{
                    EmployeeId: this.userInfo.UserId,
                    Employee: this.userInfo.UserName,
                    DepartId: this.userInfo.DepartId,
                    Depart: this.userInfo.DepartName
                    });
                    }else{				
                    Chenxin.apply(data,{
                    EmployeeId: this.applyInfo.BuyerUserId,
                    Employee: this.applyInfo.BuyerUserName,
                    DepartId: this.applyInfo.BuyerDepartId,
                    Depart: this.applyInfo.BuyerDepartName
                    });					
                    } */
                },
                scope: this
            });

        }
    },
    afterGetFormJson: function(json) {

        if (this.op == 'add') {//添加

            json.VenderCityId = this.houseInfo.CityId;
            json.VenderCompanyId = this.houseInfo.CompanyId;
            json.VenderCompanyName = this.houseInfo.CompanyName;
            json.VenderDepartId = this.houseInfo.OprDepartId;
            json.VenderUserId = this.houseInfo.OprPersonId;

            json.CommunityId = this.houseInfo.CommunityId;
            json.CommunityAddress = this.houseInfo.Address;
            json.Community = this.houseInfo.Community;

            json.CompleteYear = this.houseInfo.CompleteYear;
            json.Fitment = this.houseInfo.Fitment;

            if (this.houseInfo.Model_Room == null) {
                json.HouseType = "-/";
            } else {
                json.HouseType = this.houseInfo.Model_Room + "/";
            }
            if (this.houseInfo.Model_Hall == null) {
                json.HouseType += "-/";
            } else {
                json.HouseType += this.houseInfo.Model_Hall + "/";
            }
            if (this.houseInfo.Model_Toilet == null) {
                json.HouseType += "-";
            } else {
                json.HouseType += this.houseInfo.Model_Toilet;
            }
        }
        else {
            json.VenderDepartId = this.currentInfo.VenderDepartId;
            json.VenderUserId = this.currentInfo.VenderUserId;
            json.VenderCompanyId = this.currentInfo.VenderCompanyId;
            json.VenderCompanyName = this.currentInfo.VenderCompanyName;
            json.VenderCityId = this.currentInfo.VenderCityId;
            json.VenderCityName = this.currentInfo.VenderCityName;
        }

        var BuyerDepartId = this.findByName('BuyerDepartId');
        //下家门店
        if (BuyerDepartId.currentNode != undefined) {
            json.BuyerCityId = BuyerDepartId.currentNode.cityid;
            json.BuyerCityName = BuyerDepartId.currentNode.cityname;
            json.BuyerCompanyId = BuyerDepartId.currentNode.companyid;
            json.BuyerCompanyName = BuyerDepartId.currentNode.companyname;
        }


        if (this.op == 'confirm' || this.op == 'confirmedit' || this.op == 'confirmview') {//确认
            json.ContractDate = $('#DoneDay').val();
            json.VStanCommision = json.VStandardCommision;
            json.BStanCommision = json.BStandardCommision;
            json.ApplyId = json.RecordId;

            if (json.VRealCommision == undefined) json.VRealCommision = "0";
            if (json.BRealCommision == undefined) json.BRealCommision = "0";
            if (json.VCommision == undefined) json.VCommision = "0";
            if (json.BCommision == undefined) json.BCommision = "0";
            if (json.VConsulting == undefined) json.VConsulting = "0";
            if (json.BConsulting == undefined) json.BConsulting = "0";

            delete json.RecordId;

            if (this.op == 'confirmedit' || this.op == 'confirmview') {
                Chenxin.applyIf(json, this.currentInfo);
            }
            delete json.VStandardCommision;
            delete json.BStandardCommision;
        }

        this.additionalParam = {};


        if (this.grid.store.rows.length) {
            var rows = [];
            for (var i = 0; i < this.grid.store.rows.length; i++) {
                var row = {};
                Chenxin.apply(row, this.grid.store.rows[i]);
                if (row.MajordomoId == null) delete row.MajordomoId;
                if (row.RegionManagerId == null) delete row.RegionManagerId;
                if (row.MangerId == null) delete row.MangerId;
                if (row.DeparterManagerId == null) delete row.DeparterManagerId;
                if (row.EmployeeId == null) delete row.EmployeeId;
                if (row.DepartId == null) delete row.DepartId;
                delete row.RecordId;
                rows.push(row);
            }
            this.additionalParam.PointInfo = '[' + rows.toString() + ']';
        }



    },
    customerFormVal: function(json) {
        var total = this.grid.getTotalPoint();
        if (total != 10) {
            alert('点数10点还没有完全分配，现只分配了其中的' + total + '点');
            return false;
        }

        if (this.grid.store.rows[0]) {
            if (!this.grid.store.rows[0].DeparterManagerId) {
                alert('所有点数分配记录，必须选择店长！');
                return false;
            }
        }
        var vflag = false;
        var bflag = false;

        $.each((this.grid.store.rows), function(i, n) {
            if (this.BuyerOrVenderInfo == '10')
                vflag = true;
            if (this.BuyerOrVenderInfo == '20')
                bflag = true;
        });
        if (vflag && bflag) { }
        else {
            alert('点数分配一定要包含上下家！')
            return false;
        }

        if (!json.VRealCommision && !json.BRealCommision) {
            alert('上家佣收和下家佣收必须填写一项！')
            return false;
        }

        if ((!json.VRealCommision && json.VConsulting) || parseFloat(json.VRealCommision) < parseFloat(json.VConsulting)) {
            alert('上家咨询费不能大于上家确认佣收！')
            return false;
        }
        if ((!json.BRealCommision && json.BConsulting) || parseFloat(json.BRealCommision) < parseFloat(json.BConsulting)) {
            alert('下家咨询费不能大于下家确认佣收！')
            return false;
        }

        if (this.op == 'confirm' && !$('#DoneDay').val()) {//确认业绩的时候，成绩时间需要输入
            alert('请输入成交时间！');
            return false;
        }

        return true;
    },
    initComponent: function() {
        Chenxin.UI.BusinessApplyMain.superclass.initComponent.call(this);
        this.createGrid();
        this.initData();
    }
});

Chenxin.UI.KeyWin=Chenxin.extend(Chenxin.UI.Win,{
	id:'x_key_list_win',
	width:580,
	hasFoot:true,
	height:360,
	title:'查看钥匙信息',
	actionUrl:'/service/ContractApply/ContractApply.ashx',
	createBtn:function(){
		return [{
			text:'关闭',
			handler:this.hide
		}]	
	},
	content:'<div id="x_key_grid_win"></div>',
	createGrid:function(){
		if(!this.gird){
			this.grid=new Chenxin.UI.JsonGrid({
				id:'x_key_gird',
				renderTo:'x_key_grid_win',
				actionUrl:this.actionUrl+'?op=getkeylist',
				autoLoad:false,
				hasTitle:false,
				hasPage:false,
				hasCheckBox:false,
				columns:{
					KeyCount:{
						head:'钥匙数量',
						width:80
					},
					GetKeyDay:{
						head:'得到时间',
						width:80
					},					
					AddPerson:{
						head:'业务员',
						width:80
					},					
					AddTime:{
						head:'建档时间',
						width:80
					}
				}
			});
		}
	},
	initComponent:function(){	
		Chenxin.UI.KeyWin.superclass.initComponent.call(this);
		this.createGrid();
	}
	
});


Chenxin.UI.MarkedWin=Chenxin.extend(Chenxin.UI.Win,{
	id:'x_marked_list_win',
	width:580,
	hasFoot:true,
	height:360,
	title:'查看备案信息',
	actionUrl:'/service/ContractApply/ContractApply.ashx',
	createBtn:function(){
		return [{
			text:'关闭',
			handler:this.hide
		}]	
	},
	content:'<div id="x_marked_grid_win"></div>',
	createGrid:function(){
		if(!this.gird){
			this.grid=new Chenxin.UI.JsonGrid({
				id:'x_marked_gird',
				renderTo:'x_marked_grid_win',
				hasTitle:false,
				hasPage:false,
				autoLoad:false,
				hasCheckBox:false,
				actionUrl:this.actionUrl+'?op=getmarkedls',
				columns:{
					MarkCode:{
						head:'备案编号',
						width:80
					},
					MarkDay:{
						head:'备案日期',
						width:80
					},					
					MarkStartTime:{
						head:'备案开始日期',
						width:80
					},					
					MarkEndTime:{
						head:'备案结束日期',
						width:80
					},					
					MarkPerson:{
						head:'业务员',
						width:80
					},					
					MarkDepart:{
						head:'门店',
						width:80
					}
				}
			});
		}
	},
	initComponent:function(){	
		Chenxin.UI.MarkedWin.superclass.initComponent.call(this);
		this.createGrid();
	}
	
});


dataKeyList='Building.Type,House.Use';//设置需要获取数据字段数据的KEY,用,分割
getcity=true;//设置需要获取城市下拉框数据

$(document).ready(function(){
	var form=new Chenxin.UI.BusinessApplyMain();
})